'use strict'
var mongoose = require('mongoose')
var Department = mongoose.model('department')
var uuid = require('uuid')

exports.inquire = async (ctx, next) => {
  var offset = parseInt(ctx.query.offset) || 0
  var count = parseInt(ctx.query.limit) || 5
  var queryArray = await Department.find()
      .sort({
        'createAt': -1
      })
      .skip(offset)
      .limit(count);
  var total = await Department.estimatedDocumentCount()
  ctx.body = {
    success: true,
    objects: queryArray,
    meta: {
      total_count: total
    }
  }
}
exports.add = async (ctx, next) => {
  try {
    var body = ctx.request.body;
    var depName = await Department.findOne({depName: body.depName})
    if(depName){
      ctx.body = {
        success: false,
        message: '部门已存在'
      }
      return;
    }
    var depCode = 'HT-'+uuid.v4();
    var data = new Department({ depName: body.depName, depCode: depCode, depLead: body.depLead, depSup: body.depSup, depDescribe: body.depDescribe,depStatus: body.depStatus, depPersonnel: 1 });
    data.save();
    ctx.body = {
      success: true,
      message: '创建成功'
    }
  } catch (error) {
    ctx.body = {
      success: false,
      message: '服务器错误'
    }
  }
}
exports.update = async (ctx, next) => {
  try {
    var body = ctx.request.body;
    var msg = await Department.findByIdAndUpdate(body._id, { depName: body.depName, depLead: body.depLead, depSup: body.depSup, depDescribe: body.depDescribe, depStatus: body.depStatus })
    ctx.body = {
      success: true,
      message: '编辑成功'
    }
  } catch (error) {
    ctx.body = {
      success: false,
      message: '服务器错误'
    }
  }
}
exports.remove = async (ctx, next) => {
  try {
    var id = ctx.query && ctx.query.id
    if(id) {
      // var Department = await Department.findById(id);
      var msg = Department.findOneAndRemove({_id: id}).exec();
      if(msg){
        ctx.body = {
          success: true,
          message: '删除成功'
        }
      }else{
        ctx.body = {
          success: false,
          message: '没有该部门！'
        }
      }
    }
  } catch (error) {
    console.log('删除失败');
  }
}